package leetcode.view1715;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import leetcode.IDebug;

public class Solution2 implements IDebug {

	public String longestWord(String[] words) {
		Set<String> set = new HashSet<>();
		for (String word : words) {
			set.add(word);
		}
		Arrays.sort(words, (a, b) -> a.length() == b.length() ? a.compareTo(b) : b.length() - a.length());
		for (String word : words) {
//			set.remove(word);
			char[] cs = word.toCharArray();
			if (this.f(cs, 0, set)) {
				return new String(cs);
			}
//			set.add(word);
		}
		return "";
	}

	private boolean f(char[] cs, int index, Set<String> set) {
		if (index == cs.length) {
			return true;
		}
		for (int i = index; i < cs.length; i++) {
			if (set.contains(new String(cs, index, i - index + 1))) {
				if (index == 0 && i == cs.length - 1) {
					return false;
				}
				if (this.f(cs, i + 1, set)) {
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		char[] cs = "Hello".toCharArray();
		System.out.println(new String(cs, 1, 0));

	}

}
